#include"apue.h"
typedef struct sockaddr* sp;
#define MAXSIZE 1024
#define MAXMEN 50
int clifd[MAXMEN];
int sockfd;
static char* passwd="iqot1806";
void login(int n);
int main()
{
	struct sockaddr_in src_addr={};
	socklen_t addr_len;
	char buf[MAXSIZE]={};

	//创建
	sockfd=socket(AF_INET,SOCK_STREAM,0);
	if(0>sockfd)
	{
		perror("sockfd");
		return -1;
	}
	//准备地址
	struct sockaddr_in addr={AF_INET};
	addr.sin_port=htons(5555);
	addr.sin_addr.s_addr=inet_addr("192.168.2.3");
	//绑定
	int ret = bind(sockfd,(sp)&addr,sizeof(addr));
	if(0>ret)
	{
		perror("bind");
		return -1;
	}
	//监听
	listen(sockfd,1024);
	//记录用户人数
	int i=0;
	for(i=0;i<MAXMEN;i++)
	{
		clifd[i]=-1;
	}
	//等待连接
	while(1)
	{
		addr_len=sizeof(src_addr);
		for(i=0;i<MAXMEN;i++)
		{
			if(clifd[i]==-1)
			{
				break;
			}
		}
		clifd[i]=accept(sockfd,(sp)&src_addr,&addr_len);
		strcpy(buf,"220 (vdFTPd 3.0.2),Name:");
		write(clifd[i],buf,strlen(buf));
		//创建线程处理用户登录
		pthread_create(malloc(sizeof(pthread_t)),NULL,(void*)&login,(void*)i);
	}
}
void login(int n)
{
	char msg[MAXSIZE]={};
	char buf[MAXSIZE]={};
	char name[20];
	
//	write(clifd[n],msg,strlen(msg));
//	strcpy(msg,"Name:");
//	write(clifd[n],msg,strlen(msg));
	read(clifd[n],buf,sizeof(buf));
	if(strcmp("EOS1806",buf)!=0)
	{
		strcpy(msg,"Name error,login fail!");
		write(clifd[n],msg,strlen(msg));
		pthread_exit(0);

	}
	strcpy(msg,"331 Passwd:");
	write(clifd[n],msg,strlen(msg));
	read(clifd[n],buf,sizeof(buf));
	if(strcmp(buf,passwd)==0)
	{
		bzero(msg,sizeof(msg));
		strcpy(msg,"230 login successful!");
		write(clifd[n],msg,strlen(msg));
//		pthread_exit(0);
		while(1)
		{
			bzero(buf,sizeof(buf));
			int len =read(clifd[n],buf,sizeof(buf));
			if(len<0)
			{
				perror("read");
				close(clifd[n]);
				clifd[n]=-1;
				return;
			}
			if(strcmp(buf,"bye")==0)
			{
				printf("Welcom to use agin!\n");
				close(clifd[n]);
				clifd[n]=-1;
				return;
			}

		}
		

	}
	else
	{
		strcpy(msg,"Passwd error,login fail!");
		write(clifd[n],msg,strlen(msg));
		close(clifd[n]);
		pthread_exit(0);
	}


}

